import { reactive, ref } from "vue";
import type { Options } from "./typing";
import type { TableProps } from "ant-design-vue";

/**表格勾选默认配置 */
export const defaultOptions: Options = {
  multiple: true,
};

/**表格勾选 */
export const useTableSelect = (rowKey: string, options?: Options) => {
  const { multiple, onChange, disabledRow } = Object.assign(
    {},
    defaultOptions,
    options
  );
  const selectedRows = ref([]);

  /**勾选行 */
  const check = (record: any) => {
    const keyValue = record[rowKey];
    if (multiple) {
      rowSelection.selectedRowKeys.push(keyValue);
      selectedRows.value.push(record);
    } else {
      rowSelection.selectedRowKeys = [keyValue];
      selectedRows.value = [record];
      onChange?.(rowSelection.selectedRowKeys as string[], selectedRows.value);
    }
  };

  /**取消勾选行 */
  const unCheck = (record: any, index?: number) => {
    const findIndex = rowSelection.selectedRowKeys.findIndex(
      (f) => f == record[rowKey]
    );
    index = typeof index == "number" ? index : findIndex;
    rowSelection.selectedRowKeys.splice(index, 1);
    selectedRows.value.splice(index, 1);
  };

  const handleSelect = (record: any, selected: boolean) => {
    if (selected) check(record);
    else unCheck(record);
  };

  /**全选/反全选 */
  const handleSelectAll = (selected: boolean, _: any[], rows: any[]) => {
    for (const item of rows) {
      if (selected) check(item);
      else unCheck(item);
    }
  };

  const customRow: TableProps["customRow"] = (record: any) => {
    return {
      onClick: () => {
        // 非禁用行勾选
        if (!disabledRow?.(record)) {
          const index = rowSelection.selectedRowKeys.findIndex(
            (f) => f == record[rowKey]
          );
          if (index > -1) {
            unCheck(null, index);
          } else {
            check(record);
          }
        }
      },
    };
  };

  const clearSelect = () => {
    rowSelection.selectedRowKeys = [];
    selectedRows.value = [];
  };

  const rowSelection: TableProps["rowSelection"] = reactive({
    type: multiple ? "checkbox" : "radio",
    selectedRowKeys: [],
    onSelect: handleSelect,
    onSelectAll: handleSelectAll,
    getCheckboxProps: (record: any) => {
      return {
        disabled: disabledRow?.(record),
      };
    },
  });

  return { rowSelection, selectedRows, customRow, clearSelect };
};
